/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ibrae.mchs.radiation.entities.controllers;

import ru.ibrae.mchs.radiation.entities.Rajon;
import ru.ibrae.mchs.radiation.entities.controllers.exceptions.IllegalOrphanException;
import ru.ibrae.mchs.radiation.entities.controllers.exceptions.NonexistentEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import ru.ibrae.mchs.radiation.entities.SubjectRf;
import ru.ibrae.mchs.radiation.entities.Result;
import java.util.HashSet;
import java.util.Set;
import ru.ibrae.mchs.radiation.entities.GSPos;
import ru.ibrae.mchs.radiation.entities.Geoobject;
import java.util.ArrayList;

/**
 *
 * @author murr
 */
public class RajonJpaController {

    public RajonJpaController() {
        emf = Persistence.createEntityManagerFactory("DesktopApplication4PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Rajon rajon) {
        if (rajon.getResultSet() == null) {
            rajon.setResultSet(new HashSet<Result>());
        }
        if (rajon.getGSPosSet() == null) {
            rajon.setGSPosSet(new HashSet<GSPos>());
        }
        if (rajon.getGeoobjectSet() == null) {
            rajon.setGeoobjectSet(new HashSet<Geoobject>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            SubjectRf subjectRf = rajon.getSubjectRf();
            if (subjectRf != null) {
                subjectRf = em.getReference(subjectRf.getClass(), subjectRf.getId());
                rajon.setSubjectRf(subjectRf);
            }
            Set<Result> attachedResultSet = new HashSet<Result>();
            for (Result resultSetResultToAttach : rajon.getResultSet()) {
                resultSetResultToAttach = em.getReference(resultSetResultToAttach.getClass(), resultSetResultToAttach.getIdRezult());
                attachedResultSet.add(resultSetResultToAttach);
            }
            rajon.setResultSet(attachedResultSet);
            Set<GSPos> attachedGSPosSet = new HashSet<GSPos>();
            for (GSPos GSPosSetGSPosToAttach : rajon.getGSPosSet()) {
                GSPosSetGSPosToAttach = em.getReference(GSPosSetGSPosToAttach.getClass(), GSPosSetGSPosToAttach.getIdPoselen());
                attachedGSPosSet.add(GSPosSetGSPosToAttach);
            }
            rajon.setGSPosSet(attachedGSPosSet);
            Set<Geoobject> attachedGeoobjectSet = new HashSet<Geoobject>();
            for (Geoobject geoobjectSetGeoobjectToAttach : rajon.getGeoobjectSet()) {
                geoobjectSetGeoobjectToAttach = em.getReference(geoobjectSetGeoobjectToAttach.getClass(), geoobjectSetGeoobjectToAttach.getIdNp());
                attachedGeoobjectSet.add(geoobjectSetGeoobjectToAttach);
            }
            rajon.setGeoobjectSet(attachedGeoobjectSet);
            em.persist(rajon);
            if (subjectRf != null) {
                subjectRf.getRajonSet().add(rajon);
                subjectRf = em.merge(subjectRf);
            }
            for (Result resultSetResult : rajon.getResultSet()) {
                Rajon oldRajonOfResultSetResult = resultSetResult.getRajon();
                resultSetResult.setRajon(rajon);
                resultSetResult = em.merge(resultSetResult);
                if (oldRajonOfResultSetResult != null) {
                    oldRajonOfResultSetResult.getResultSet().remove(resultSetResult);
                    oldRajonOfResultSetResult = em.merge(oldRajonOfResultSetResult);
                }
            }
            for (GSPos GSPosSetGSPos : rajon.getGSPosSet()) {
                Rajon oldRajonOfGSPosSetGSPos = GSPosSetGSPos.getRajon();
                GSPosSetGSPos.setRajon(rajon);
                GSPosSetGSPos = em.merge(GSPosSetGSPos);
                if (oldRajonOfGSPosSetGSPos != null) {
                    oldRajonOfGSPosSetGSPos.getGSPosSet().remove(GSPosSetGSPos);
                    oldRajonOfGSPosSetGSPos = em.merge(oldRajonOfGSPosSetGSPos);
                }
            }
            for (Geoobject geoobjectSetGeoobject : rajon.getGeoobjectSet()) {
                Rajon oldRajonOfGeoobjectSetGeoobject = geoobjectSetGeoobject.getRajon();
                geoobjectSetGeoobject.setRajon(rajon);
                geoobjectSetGeoobject = em.merge(geoobjectSetGeoobject);
                if (oldRajonOfGeoobjectSetGeoobject != null) {
                    oldRajonOfGeoobjectSetGeoobject.getGeoobjectSet().remove(geoobjectSetGeoobject);
                    oldRajonOfGeoobjectSetGeoobject = em.merge(oldRajonOfGeoobjectSetGeoobject);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Rajon rajon) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Rajon persistentRajon = em.find(Rajon.class, rajon.getIdRajon());
            SubjectRf subjectRfOld = persistentRajon.getSubjectRf();
            SubjectRf subjectRfNew = rajon.getSubjectRf();
            Set<Result> resultSetOld = persistentRajon.getResultSet();
            Set<Result> resultSetNew = rajon.getResultSet();
            Set<GSPos> GSPosSetOld = persistentRajon.getGSPosSet();
            Set<GSPos> GSPosSetNew = rajon.getGSPosSet();
            Set<Geoobject> geoobjectSetOld = persistentRajon.getGeoobjectSet();
            Set<Geoobject> geoobjectSetNew = rajon.getGeoobjectSet();
            List<String> illegalOrphanMessages = null;
            for (GSPos GSPosSetOldGSPos : GSPosSetOld) {
                if (!GSPosSetNew.contains(GSPosSetOldGSPos)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain GSPos " + GSPosSetOldGSPos + " since its rajon field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (subjectRfNew != null) {
                subjectRfNew = em.getReference(subjectRfNew.getClass(), subjectRfNew.getId());
                rajon.setSubjectRf(subjectRfNew);
            }
            Set<Result> attachedResultSetNew = new HashSet<Result>();
            for (Result resultSetNewResultToAttach : resultSetNew) {
                resultSetNewResultToAttach = em.getReference(resultSetNewResultToAttach.getClass(), resultSetNewResultToAttach.getIdRezult());
                attachedResultSetNew.add(resultSetNewResultToAttach);
            }
            resultSetNew = attachedResultSetNew;
            rajon.setResultSet(resultSetNew);
            Set<GSPos> attachedGSPosSetNew = new HashSet<GSPos>();
            for (GSPos GSPosSetNewGSPosToAttach : GSPosSetNew) {
                GSPosSetNewGSPosToAttach = em.getReference(GSPosSetNewGSPosToAttach.getClass(), GSPosSetNewGSPosToAttach.getIdPoselen());
                attachedGSPosSetNew.add(GSPosSetNewGSPosToAttach);
            }
            GSPosSetNew = attachedGSPosSetNew;
            rajon.setGSPosSet(GSPosSetNew);
            Set<Geoobject> attachedGeoobjectSetNew = new HashSet<Geoobject>();
            for (Geoobject geoobjectSetNewGeoobjectToAttach : geoobjectSetNew) {
                geoobjectSetNewGeoobjectToAttach = em.getReference(geoobjectSetNewGeoobjectToAttach.getClass(), geoobjectSetNewGeoobjectToAttach.getIdNp());
                attachedGeoobjectSetNew.add(geoobjectSetNewGeoobjectToAttach);
            }
            geoobjectSetNew = attachedGeoobjectSetNew;
            rajon.setGeoobjectSet(geoobjectSetNew);
            rajon = em.merge(rajon);
            if (subjectRfOld != null && !subjectRfOld.equals(subjectRfNew)) {
                subjectRfOld.getRajonSet().remove(rajon);
                subjectRfOld = em.merge(subjectRfOld);
            }
            if (subjectRfNew != null && !subjectRfNew.equals(subjectRfOld)) {
                subjectRfNew.getRajonSet().add(rajon);
                subjectRfNew = em.merge(subjectRfNew);
            }
            for (Result resultSetOldResult : resultSetOld) {
                if (!resultSetNew.contains(resultSetOldResult)) {
                    resultSetOldResult.setRajon(null);
                    resultSetOldResult = em.merge(resultSetOldResult);
                }
            }
            for (Result resultSetNewResult : resultSetNew) {
                if (!resultSetOld.contains(resultSetNewResult)) {
                    Rajon oldRajonOfResultSetNewResult = resultSetNewResult.getRajon();
                    resultSetNewResult.setRajon(rajon);
                    resultSetNewResult = em.merge(resultSetNewResult);
                    if (oldRajonOfResultSetNewResult != null && !oldRajonOfResultSetNewResult.equals(rajon)) {
                        oldRajonOfResultSetNewResult.getResultSet().remove(resultSetNewResult);
                        oldRajonOfResultSetNewResult = em.merge(oldRajonOfResultSetNewResult);
                    }
                }
            }
            for (GSPos GSPosSetNewGSPos : GSPosSetNew) {
                if (!GSPosSetOld.contains(GSPosSetNewGSPos)) {
                    Rajon oldRajonOfGSPosSetNewGSPos = GSPosSetNewGSPos.getRajon();
                    GSPosSetNewGSPos.setRajon(rajon);
                    GSPosSetNewGSPos = em.merge(GSPosSetNewGSPos);
                    if (oldRajonOfGSPosSetNewGSPos != null && !oldRajonOfGSPosSetNewGSPos.equals(rajon)) {
                        oldRajonOfGSPosSetNewGSPos.getGSPosSet().remove(GSPosSetNewGSPos);
                        oldRajonOfGSPosSetNewGSPos = em.merge(oldRajonOfGSPosSetNewGSPos);
                    }
                }
            }
            for (Geoobject geoobjectSetOldGeoobject : geoobjectSetOld) {
                if (!geoobjectSetNew.contains(geoobjectSetOldGeoobject)) {
                    geoobjectSetOldGeoobject.setRajon(null);
                    geoobjectSetOldGeoobject = em.merge(geoobjectSetOldGeoobject);
                }
            }
            for (Geoobject geoobjectSetNewGeoobject : geoobjectSetNew) {
                if (!geoobjectSetOld.contains(geoobjectSetNewGeoobject)) {
                    Rajon oldRajonOfGeoobjectSetNewGeoobject = geoobjectSetNewGeoobject.getRajon();
                    geoobjectSetNewGeoobject.setRajon(rajon);
                    geoobjectSetNewGeoobject = em.merge(geoobjectSetNewGeoobject);
                    if (oldRajonOfGeoobjectSetNewGeoobject != null && !oldRajonOfGeoobjectSetNewGeoobject.equals(rajon)) {
                        oldRajonOfGeoobjectSetNewGeoobject.getGeoobjectSet().remove(geoobjectSetNewGeoobject);
                        oldRajonOfGeoobjectSetNewGeoobject = em.merge(oldRajonOfGeoobjectSetNewGeoobject);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = rajon.getIdRajon();
                if (findRajon(id) == null) {
                    throw new NonexistentEntityException("The rajon with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Rajon rajon;
            try {
                rajon = em.getReference(Rajon.class, id);
                rajon.getIdRajon();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The rajon with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Set<GSPos> GSPosSetOrphanCheck = rajon.getGSPosSet();
            for (GSPos GSPosSetOrphanCheckGSPos : GSPosSetOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Rajon (" + rajon + ") cannot be destroyed since the GSPos " + GSPosSetOrphanCheckGSPos + " in its GSPosSet field has a non-nullable rajon field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            SubjectRf subjectRf = rajon.getSubjectRf();
            if (subjectRf != null) {
                subjectRf.getRajonSet().remove(rajon);
                subjectRf = em.merge(subjectRf);
            }
            Set<Result> resultSet = rajon.getResultSet();
            for (Result resultSetResult : resultSet) {
                resultSetResult.setRajon(null);
                resultSetResult = em.merge(resultSetResult);
            }
            Set<Geoobject> geoobjectSet = rajon.getGeoobjectSet();
            for (Geoobject geoobjectSetGeoobject : geoobjectSet) {
                geoobjectSetGeoobject.setRajon(null);
                geoobjectSetGeoobject = em.merge(geoobjectSetGeoobject);
            }
            em.remove(rajon);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Rajon> findRajonEntities() {
        return findRajonEntities(true, -1, -1);
    }

    public List<Rajon> findRajonEntities(int maxResults, int firstResult) {
        return findRajonEntities(false, maxResults, firstResult);
    }

    private List<Rajon> findRajonEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Rajon.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Rajon findRajon(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Rajon.class, id);
        } finally {
            em.close();
        }
    }

    public int getRajonCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Rajon> rt = cq.from(Rajon.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
